import { reqGetUserInfo, reqLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'
// 清除后期自己来写
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}, // 用户信息
    routes: constantRoutes // 使用vuex维护路由规则
  },
  mutations: {
    // 设置token的方法
    setToken(state, payload) {
      state.token = payload // 存储token到vuex
      // 存储token到本地
      setToken(payload)
    },
    // 设置用户信息
    setInfo(state, payload) {
      state.userInfo = payload
    },
    // 退出的mutation, 清除token和用户信息
    logout(state) {
      state.token = ''
      removeToken()
      state.userInfo = {}
      // 重置路由
      resetRouter()
      state.routes = constantRoutes
    },
    // 添加routes数据
    addFilterRoutes(state, routes) {
      state.routes = [...constantRoutes, ...routes]
    }
  },
  actions: {
    // 登录action
    async login({ commit }, data) {
      const res = await reqLogin(data)
      console.log(res)
      commit('setToken', res.data)
    },
    //  获取用户信息
    async getInfo({ commit }) {
      const { data } = await reqGetUserInfo()
      commit('setInfo', data)
      return data // 将个人信息返回. 处理权限
    }
  }
}

